package com.hxzy.controller;

import com.alibaba.fastjson.JSONObject;
import com.hxzy.util.RedisUtil;
import com.hxzy.util.StringUtil;
import com.hxzy.common.BaseServlet;
import com.hxzy.common.ResultAjax;
import com.wf.captcha.ArithmeticCaptcha;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description:
 * @Author: ykj
 * @Date: 2022/3/3 20:53
 */
@WebServlet(urlPatterns = "/captcha")
public class CaptchaServlet extends BaseServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int width=150;
        int height=50;
        String width1 = req.getParameter("width");
        if (StringUtil.isNotBlank(width1)&&StringUtil.isIntGtZore(width1)){
            width=Integer.parseInt(width1);
        }
        String height1 = req.getParameter("height");
        if (StringUtil.isNotBlank(height1)&& StringUtil.isIntGtZore(height1)){
            height = Integer.parseInt(height1);
        }

        // 算术类型
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(width, height);
        captcha.setLen(2);  // 几位数运算，默认是两位

        String text = captcha.text();// 获取运算的结果：5
        //将图片转化stream转为为 byte[]
        String images = captcha.toBase64();
        //把图片的值，存放到redis中,然后给一个过期时间

        Jedis jedis = RedisUtil.create();
        //使用String存储,set(键,value)
        String id=req.getSession().getId();//或 UUID.randomUUID().toString()
        String redisKey="captcha:"+id;
        jedis.setex(redisKey, 300, text);
        //输出给前段
        ResultAjax success = ResultAjax.success(images);
        success.put("uuid", id);
        super.render(resp, JSONObject.toJSONString(success));
        
    }
}
